import React,{Component} from 'react';

export default class LifeCyle extends Component {

  constructor() {

    super(); 
    this.state = {
      number:0,
      users:[]
    }

    console.log('1. constructor 执行完成')

  }

  componentWillMount() {

    console.log('2. componentWillMount 组件将要被挂载时');
  }

  componentDidMount() {

    console.log('4. componentDidMount 组件挂载(渲染)完成时');

    fetch('http://api.github.com/users')
      .then(res => res.json())
      .then( users => {
        console.log(users);
        this.setState({users:users});
      })
  }

  shouldComponentUpdate(nextProps,nextState) {

    console.log('5. shouldComponentUpdate 询问组件是否需要更新');
    if(nextState.number == this.state.number) {

      return false;
    }

    return true;
    


  }

  componentWillUpdate () {

    console.log( ' 6. componentWillUpdate 组件即将更新')
  }

  componentDidUpdate() {

    console.log('7 . componentDidUpdate 组件更新完成')
  }



  render() {
    console.log('3. render 开始执行')
    return (
      <>
        <div style={{border:'5px solid red',padding:'5px'}}>
          <p>{this.props.name}:{this.state.number}</p>
          {/* this 丢失 */}
          <button onClick={this.add.bind(this)} >+</button>


        </div>

        <div>{this.state.number % 2 == 0 && <SubCounter number={this.state.number} />}</div>
        <ul>
          {/* {
            this.state.users.map(user => (<li key={user.id}>{user.login}</li>))
          } */}
        </ul>
      </>
    )
  }

  add() {

    this.setState(
      {
        number:this.state.number + 1
      }
    )
  }
}

// 可拔插的组件
class SubCounter extends Component{

  constructor(props) {

    super(props);
    this.state = {
      number:props.number
    }
  }

  // 子组件的生命周期
  componentWillReceiveProps() {

    console.log('SubCounter 1. componentWillReceiveProps');
  }

  componentWillUnmount() {
    console.log('SubCounter componentWillUnmount');
  }

  render() {

    console.log('SubCounter 3. render')
    return (
      <div>
        <div>number:{this.state.number}</div>
      </div>
    )

  }
 
}